package com.blb.controller.front;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.entity.*;
import com.blb.service.*;
import com.blb.utils.EmailUtil;
import com.blb.utils.RandomValidateCodeUtil;
import com.blb.utils.UUIDUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author txy
 * @since 2019-07-16
 */
@Controller
@RequestMapping("/front/frontUser")
public class FrontUserController {


    @Autowired
    private IFrontUserService frontUserService;

    @Autowired
    private IKeywordService keywordService;

    @Autowired
    private IProductTypeService productTypeService;

    @Autowired
    private ISlideshowService slideshowService;

    @Autowired
    private ICommodityService commodityService;

    @Autowired
    private ICartService cartService;

    /**
     * 跳转
     *
     * @return
     */
    @RequestMapping("register")
    public String register() {
        return "/front/register";
    }

    /**
     *发送验证码，并使用session存储设置值
     */
    @ResponseBody
    @RequestMapping("email")
    public String vcode(String email, Model model) throws ServletException, IOException, SQLException {
        String code = new EmailUtil().achieveCode();  //生成随机密码
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("code", code);
        try {
            EmailUtil.send_mail(email, code);
            System.out.println("邮件发送成功!");
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            return "发送失败";
        }

    }

    /**
     * 注册
     * @param frontUser
     * @param code
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping("registerUser")
    public String registerUser(FrontUser frontUser, @Param("code") String code, Model model) {
        Session session = SecurityUtils.getSubject().getSession();
        String trueCode = (String) session.getAttribute("code");

        //验证码
        if (trueCode == null || !trueCode.equals(code)) {
            return "验证码错误";
        }
        //邮箱
        List<FrontUser> emailList = frontUserService.isEmail(frontUser.getEmail());
        if(!emailList.isEmpty()){
            return "邮箱已被注册";
        }
        //用户名
        List<FrontUser> usernameList = frontUserService.isFrontUser(frontUser.getUsername());
        if(!usernameList.isEmpty()){
            return "用户名已存在";
        }
        frontUser.setId(UUIDUtils.getID());
        frontUser.setSalt(UUIDUtils.getID());
        frontUser.setCreateTime(new Date());

        //加密后的密码
        frontUser.setPassword(new SimpleHash("MD5", frontUser.getPassword(), frontUser.getSalt(), 1024).toString());
        frontUserService.save(frontUser);

        //给用户创建购物车
        Cart cart = new Cart();
        cart.setUserId(frontUser.getId());
        cart.setId(frontUser.getId());
        cartService.save(cart);

        return "";
    }

    /**
     * 跳转登录
     * @return
     */
    @RequestMapping("goLogin")
    public String login(){
        return "front/login";
    }

    /**
     * 跳转注册
     */
    @RequestMapping("goRegister")
    public String goRegister(){
        return "front/register";
    }


    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getCode")
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验验证码
     */
    @ResponseBody
    @RequestMapping(value = "/login")
    public String checkVerify(String username,String password,String code,String avoidLogin, HttpSession session,HttpServletRequest request,HttpServletResponse response) {

        //从session中获取随机数
        String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
        if (!random.equals(code)) {
            return "验证码错误";
        }
        FrontUser frontUser = frontUserService.getOne(new QueryWrapper<FrontUser>().eq("username", username));
        if(frontUser==null){
            return "用户名不存在";
        }
        String truePassword = frontUser.getPassword();
        String ispassword = new SimpleHash("MD5", password, frontUser.getSalt(), 1024).toString();
        if(!truePassword.equals(ispassword)){
            return "密码错误";
        }

        //七天免登陆
        if(avoidLogin.equals("true")){
            FrontUser frontUser1 = frontUserService.getOne(new QueryWrapper<FrontUser>().eq("username", username));
            Cookie idCookie = new Cookie("id", frontUser1.getId());
            idCookie.setMaxAge(60*60*24*7);
            Cookie usernameCookie = new Cookie("username", username);
            usernameCookie.setMaxAge(60*60*24*7);
            Cookie passwordCookie = new Cookie("password", password);
            passwordCookie.setMaxAge(60*60*24*7);

            //该cookie在哪些网址下有效
            idCookie.setPath("/");
            usernameCookie.setPath("/");
            passwordCookie.setPath("/");
            response.addCookie(idCookie);
            response.addCookie(usernameCookie);
            response.addCookie(passwordCookie);

        }
        session.setAttribute("frontUser",frontUser);
        return "";
    }

    /**
     * 跳转index
     * @return
     */
    @RequestMapping("goindex")
    public String goindex(Model model,HttpSession session){

        //关键词根据次数排序前十条数据
        List<Keyword> keywordTop = keywordService.getKeywordTop();
        model.addAttribute("keywordTop",keywordTop);

        //获取分类的前九条数据
        List<Comtype> comtype = productTypeService.getComtype();
        model.addAttribute("comtypes",comtype);

        //获取轮播图
        List<Slideshow> slideshow = slideshowService.getSlideshow();
        model.addAttribute("slideshows",slideshow);

        //获取新品
        List<Commodity> newCommodity = commodityService.getNewCommodity();
        model.addAttribute("newCommoditys" ,newCommodity);

        //分类序号为1的前五条数据
        List<Commodity> commodityOne = commodityService.getCommodityByTypeId(comtype.get(0).getId()).subList(0,5);
        model.addAttribute("commoditysOne",commodityOne);

        //分类序号为2的前十二条数据
        List<Commodity> commodityTwo = commodityService.getCommodityByTypeId(comtype.get(1).getId()).subList(0, 12);
        model.addAttribute("commoditysTwo",commodityTwo);

        //分类序号为3的前五条数据
        List<Commodity> commodityThree = commodityService.getCommodityByTypeId(comtype.get(2).getId()).subList(0, 5);
        model.addAttribute("commoditysThree",commodityThree);

        //分类序号为4的前十二条数据
        List<Commodity> commodityFour = commodityService.getCommodityByTypeId(comtype.get(3).getId()).subList(0, 12);
        model.addAttribute("commoditysFour",commodityFour);

        //获取排行数据
        List<Commodity> mroeCommodity = commodityService.getMroeCommodity();
        model.addAttribute("mroeCommoditys",mroeCommodity);
        return "front/index";
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping("frontLogOut")
    public String LogOut(HttpServletRequest request,HttpServletResponse response,HttpSession session){

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if("username".equals(cookie.getName())||"password".equals(cookie.getName()) || "id".equals(cookie.getName())){
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        session.removeAttribute("frontUser");

        return "redirect:/front/frontUser/goindex";
    }

}

